package com.bootdo.clouddo.service.user;

import cn.binarywang.wx.miniapp.api.impl.WxMaServiceImpl;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.bean.WxMaPhoneNumberInfo;
import cn.binarywang.wx.miniapp.bean.WxMaUserInfo;
import cn.binarywang.wx.miniapp.config.impl.WxMaDefaultConfigImpl;
import com.bootdo.clouddo.config.WxMpConfig;
import com.bootdo.clouddo.utils.StringUtils;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.io.File;

@Service
public class WxService extends WxMaServiceImpl {

	@Autowired
	private WxMpConfig wxMpConfig;

	@PostConstruct
	public void init() {
		WxMaDefaultConfigImpl config = new WxMaDefaultConfigImpl();
		// 设置微信的appid
		config.setAppid(wxMpConfig.getAppid());
		// 设置微信的app corpSecret
		config.setSecret(wxMpConfig.getAppSecret());
		// 设置微信token
		config.setToken(wxMpConfig.getToken());
		// 设置消息加解密密钥
		config.setAesKey(wxMpConfig.getAesKey());

        super.setWxMaConfig(config);
	}

	/**
	 * 通过code换取session信息
	 * @param code
	 * @return
	 */
	public WxMaJscode2SessionResult getSessionInfoByCode(String code) {
		try {
			return getUserService().getSessionInfo(code);
		} catch (WxErrorException e) {
			e.printStackTrace();
		} catch (Exception e2){
			e2.printStackTrace();
		}
		return null;
	}

	/**
	 * <pre>
	 * 获取用户信息接口
	 * </pre>
	 */
	public WxMaUserInfo getUserInfo(String sessionKey, String encryptedData, String iv) {
		// 解密用户信息
		try{
			return getUserService().getUserInfo(sessionKey, encryptedData, iv);
		}catch (Exception e){
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * <pre>
	 * 获取用户绑定手机号信息
	 * </pre>
	 */
	public WxMaPhoneNumberInfo getUserPhone(String sessionKey, String encryptedData, String iv) {
		try{
			return getUserService().getPhoneNoInfo(sessionKey, encryptedData, iv);
		}catch (Exception e){
			e.printStackTrace();
		}
		return null;
	}

	public boolean checkMsg(String msg){
		try{
			if(StringUtils.isBlank(msg)) {
				return true;
			}
			return getSecCheckService().checkMessage(msg);
		}catch (Exception e){
			e.printStackTrace();
		}
		return true;
	}

	public boolean checkImage(File file){
		try{
			getSecCheckService().checkImage(file);
			return false;
		}catch (Exception e){
			e.printStackTrace();
		}
		return true;
	}


}
